package com.lee.security.provider.social.impl;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.lee.security.provider.social.SocialTokenCheck;
import jodd.http.HttpRequest;
import jodd.http.HttpResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.task.TaskExecutor;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Objects;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Future;

/**
 * @author lee
 * @date 2018年11月21日
 */
@Component
public class QQTokenCheck implements SocialTokenCheck {

    @Autowired
    private ObjectMapper objectMapper;

    @Autowired
    private TaskExecutor myTaskExecutor;

    private static final String raw_url = "https://graph.qq.com/user/get_user_info?oauth_consumer_key=%s&openid=%s&access_token=%s";

    private static final String oauth_consumer_key = "1107958542";

    @Override
    public Future<Boolean> tokenCheck(String openId, String socialToken) {
        return CompletableFuture.supplyAsync(() -> {
            String url = String.format(raw_url, oauth_consumer_key, openId, socialToken);
            HttpRequest httpRequest = HttpRequest.get(url).acceptEncoding("UTF-8");
            HttpResponse httpResponse = httpRequest.send();
            String body = httpResponse.bodyText();
            JsonNode readNode;
            try {
                readNode = objectMapper.readTree(body);
            } catch (IOException e) {
                return false;
            }
            Number ret = readNode.path("ret").numberValue();
            return Objects.equals(ret, 0);
        }, myTaskExecutor).exceptionally(e -> false);

    }

}
